//index.js
//获取应用实例
var app = getApp()

Page({
  data: {
    latitude: '',
    longitude: '',
    markers: [],
    info: [],
    details: {},
    isShowDetails: false,
    controls: [],
    isAuth: true
  },
  onLoad: function (options) {

    const that = this
    // 查看是否授权
    wx.getSetting({

      success: function (res) {
        
        if (res.authSetting['scope.userInfo']) {

          //console.log('已经授权' + wx.getStorageSync('uid'));
          wx.checkSession({
            success: function () {
              console.log("未过期，并且在本生命周期一直有效");
              var uid = wx.getStorageSync('uid');
              if (uid) {
                app.getUserInfoFromServer(uid, function (userinfo) {

                  console.log("tang" + app.globalData.openid);

                });
              } else {
                //没有授权 默认授权
                that.setData({
                  isAuth: false
                });
              }

            },
            fail: function () {
              console.log("已经失效，需要重新执行登录流程");

              var uid = wx.getStorageSync('uid');

              if (uid) {

                app.getUserInfoLogin(uid, function (userinfo) {

                  console.log(userinfo);
                });
              } else {
                //没有授权 默认授权
                that.setData({
                  isAuth: false
                });
              }
            }
          })

        } else {
          that.setData({
            isAuth: false
          });
          //没有授权 默认授权
        }
      }
    })

    that.showMap()
    that.getCenter()
  },
  onReady: function () {
    this.mapCtx = wx.createMapContext('myMap')
  },

  /**
   * 获取详细位置坐标信息
   */
  getDetails: function (lat,lng) {
    const that = this
    wx.request({
      url: app.globalData.website + 'Orderform/getMap',
      data: {
        lat: lat,
        lng: lng
      },
      success: function (res) {
        console.log("tan1" + res.data.data)
        that.setData({
          info: res.data.data
        })
        // console.log(that.data.info)
        const info = that.data.info
        const markers = []
        for (var i = 0; i < info.length; i++) {
         
          var iconPath = ''
          if (info[i].imgpaths == null) {
            iconPath = '../../images/icon_F.png'
          } else {
            // iconPath = info[i].imgpaths
            iconPath = '../../images/icon_F.png'
          }
          markers.push({
            id: i, latitude: info[i]["latitude"], longitude: info[i]["longitude"], iconPath: iconPath, width: 40, height: 40, })
        }
        that.setData({
          markers: markers
        })
        // console.log(that.data.markers)
      }
    })
  },
  /**
   * 获取中心点坐标
   */
  getCenter: function () {
    const that = this
    wx.getSystemInfo({
      success: function (res) {
        var width = res.windowWidth
        var height = res.windowHeight
        var left = width / 2
        var top = height / 2 - 50
        var controls = []
        controls.push({ position: { left: left, top: top, width: 20, height: 30 }, iconPath: '../../images/icon_index_mark.png' })
        that.setData({
          controls: controls
        })
      },
    })
  },
  /**
   * 绘制地图
   */
  showMap: function () {
    const that = this
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        const lat = res.latitude
        const long = res.longitude
        that.setData({
          latitude: lat,
          longitude: long
        })
        that.getDetails(lat, long)
      }
    })
  },
  /**
   * 点击个人中心按钮
   */
  showPersonal: function () {
    wx.navigateTo({
      url: '../personal/index'
    })
  },

  publish: function () {
    wx.navigateTo({
      url: '../publish/index'
    })
  },
  /**
   * 点击扫码充电按钮
   */
  scanBtn: function () {
    // wx.navigateTo({
    //   url: '../lease/index'
    // })
    wx.scanCode({
      onlyFromCamera: true,
      success: function (res) {
        console.log(res)
        wx.request({
          url: app.globalData.website + 'webchat/doScan',
          data: {
            qrurl: res.result.substring(res.result.lastIndexOf("/") + 1),
            openid: 'o20PM4kEGngsUwlN6_lGLiTmWaS4'
          },
          success: function (res) {
            console.log(res)
            wx.setStorageSync('scanInfo', res.data.data)
            wx.navigateTo({
              url: '../recharge/index'
            })
          }
        })
      }
    })  
  },
  /**
   * 点击标记显示详细信息
   */
  showMarket: function (e) {
    // console.log(e.markerId)
    // console.log(this.data.info[e.markerId])
    var info = this.data.info[(e.markerId)]
    const that = this
    var details = this.data.details
    details.name = info.content
    details.phone = info.phone
    details.reward = info.reward
    details.latitude = info.latitude
    details.longitude = info.longitude
    that.setData({
      isShowDetails: true,
      details: details
    })
  },
  callphone: function (e) {
   
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.id //仅为示例，并非真实的电话号码
    })
  },
  /**
   * 点击地图时触发事件
   */
  mapEvent: function () {
    const that = this
    that.setData({
      isShowDetails: false
    })
  },
  /**
   * 点击按钮跳转到详情 立即租借
   */
  showDetails: function () {
    wx.navigateTo({
      url: '../lease/index'
    })
  },
  /**
   * 点击按钮重新定位
   */
  reLocation: function () {
    const that = this
    that.showMap()
  },
  /**
   * 获取中心位置坐标
   */
  getCenterLocation: function () {
    const that = this
    that.mapCtx.getCenterLocation({
      success: function (res) {
        var longitude = res.longitude
        var latitude = res.latitude
        that.getDetails(latitude, longitude)
      }
    })
  },

  /**
   * 视野发生变化时触发
   */
  regionChange: function () {
    console.log('视野变化')
    const that = this
    that.getCenterLocation()
  },

  /**
 * 点击按钮隐藏
 */
  hiddenModal: function () {
    const that = this
    that.setData({
      isAuth: true
    })
  },

  /**
 * 获取用户信息
 */
  getUserInfo: function (res) {
    console.log(res)
    var detail = res.detail;
    var that = this;

    if (detail.errMsg == "getUserInfo:ok") {
      this.setData({
        isAuth: true
      })

      var encryptedData = detail.encryptedData;
      var iv = detail.iv;

      app.getUserInfo(encryptedData, iv, function (userinfo) {

        console.log(userinfo);

      });
    }

    if (res.detail.errMsg == "getUserInfo:fail auth deny") {
      //点击了拒绝授权
      that.setData({
        isAuth: false
      })
    }
  },
  /**
   * 显示详细位置，定位
   */
  showMapDetails: function () {
    const that = this
    var latitude = that.data.details.latitude
    var longitude = that.data.details.longitude 
    wx.openLocation({
      latitude: latitude,
      longitude: longitude
    })
  }
})
